package com.overlord.im.connector.netty.handler;

import com.google.common.base.Throwables;
import com.overlord.im.commons.message.OverlordImMessage;
import com.overlord.im.connector.message.resolver.MessageResolverFactory;
import com.overlord.im.connector.message.resolver.Resolver;
import com.overlord.im.connector.netty.connector.ConnectorContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ImServiceHandler
 * @Author wuwei
 * @Description NONE
 * @Date 2020/5/29 14:33
 **/
@Slf4j
public class ImServiceHandler extends SimpleChannelInboundHandler<OverlordImMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, OverlordImMessage overlordImMessage)
        throws Exception {
        Resolver resolver = MessageResolverFactory.resolver(overlordImMessage);
        resolver.resolve(overlordImMessage, channelHandlerContext);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端已连接...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开连接...");
        ConnectorContext.remove(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("连接异常:{}", Throwables.getStackTraceAsString(cause));
    }

}
